const Controller = require('egg').Controller;
const { ObjectId } = require('mongodb');
class CollectController extends Controller {
  async index() {
    const { ctx } = this;
    var { id, collected } = ctx.request.body;
    var db = this.app.mongodb;
    await db.collection('article').updateOne({ _id: ObjectId(id) }, { $set: { collected: collected } });
    var res = await ctx.service.article.find(id);
    var item = res[0];  //必须转为对象格式才可以传
    try {
      if (collected) {
        await db.collection('user').insertOne(item);
        ctx.body = {
          status: 200,
          msg: '收藏成功',
        };
      } else {
        await db.collection('user').deleteOne({ _id: ObjectId(id) });
        ctx.body = {
          status: 200,
          msg: '取消收藏',
        };
      }
    } catch (err) {
      this.app.logger.error(err);
    }
  }
}

module.exports = CollectController;
